﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;


using ECCIT;
using ECCIT.Data;
using ECCIT.Business.Model;
using ECCIT.Business.DAL;

using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;
using System.Configuration;
using System.Data.SqlClient;
namespace OgilvyOne.UKNow.DAL
{
    public class LogKeyWordsDAL : UKNowBaseDAL
    {
        public LogKeyWordsDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        public override string TableName
        {
            get { throw new NotImplementedException(); }
        }

        public override IField[] SelectFields
        {
            get { throw new NotImplementedException(); }
        }

        public override IField[] UpdateFields
        {
            get { throw new NotImplementedException(); }
        }

        public override ECCIT.Data.IField[] InsertFields
        {
            get { throw new NotImplementedException(); }
        }

        public override Type ModelType
        {
            get { throw new NotImplementedException(); }
        }

        public ResultInfo InsertLog(Dictionary<MapKeyWordsModel ,int>  dmm,int COMMENT_ID,int COMMENT_Type)
        {
            ResultInfo result = new ResultInfo(false);
            string cmd = String.Format("insert into UKNOW_KEYWORD_LOG values()");
            try
            {
                int count = 0;
                foreach (MapKeyWordsModel mwm in dmm.Keys)
                {
                    for (int i = 0; i <dmm[mwm]; i++)
                    {
                        IDataParameter[] parms = new IDataParameter[] { new SqlParameter("@COL_LOG_INSERT_TIME", DbType.DateTime) };
                        parms[0].Value = DateTime.Now;

                        cmd=String.Format("insert into UKNOW_KEYWORD_LOG (COL_LANG_ID,COL_KEYWORD_ID,COL_COMMENT_ID,COL_COMMENT_TYPE,COL_LOG_INSERT_TIME) values({0},{1},{2},{3},@COL_LOG_INSERT_TIME)",mwm.LanguageID,mwm.ID,COMMENT_ID,COMMENT_Type);
                        DBHelper.ExecuteNonQuery(cmd, parms);
                        count++;
                    }
                }
                if (count > 0)
                    result.Result = true;
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = ex.Message;
            }

            return result;
        }

        public IList<MapKeyWordsModel> GetAllLogKeyWordsModels()
        {
            string cmd = string.Format("select * from {0} where {1}={2}", "UKNOW_MAP_KEYWORD", "col_lang_id", (int)this.Language.LanguageType);
            IList<MapKeyWordsModel> models = new List<MapKeyWordsModel>();
            using (IDataReader reader = DBHelper.ExecuteReader(cmd))
            {
                while (reader.Read())
                {
                    MapKeyWordsModel model = new MapKeyWordsModel((int)this.Language.LanguageType,
                        (int?)reader["COL_KEYWORD_ID"], (string)reader["COL_KEYWORD_NAME"], (int?)reader["COL_KEYWORD_TYPE"], (int?)reader["COL_KEYWORD_COUNT"],
                        (int?)reader["COL_KEYWORD_STATE"], (DateTime?)reader["COL_KEYWORD_INSERT_TIME"], (DateTime?)reader["COL_KEYWORD_UPDATE_TIME"]);

                    models.Add(model);
                }
            }
            return models;
        }

        public MapKeyWordsModel GetLogKeyWordsModelByID(int keywordID)
        {
            string cmd = string.Format("select * from {0} where {1}={2} and {3}={4}", "UKNOW_MAP_KEYWORD", "col_lang_id", (int)this.Language.LanguageType,
                "COL_KEYWORD_ID", keywordID);

            MapKeyWordsModel model = null;
            using (IDataReader reader = DBHelper.ExecuteReader(cmd))
            {
                while (reader.Read())
                {
                    model = new MapKeyWordsModel((int)this.Language.LanguageType,
                        (int?)reader["COL_KEYWORD_ID"], (string)reader["COL_KEYWORD_NAME"], (int?)reader["COL_KEYWORD_TYPE"], (int?)reader["COL_KEYWORD_COUNT"],
                        (int?)reader["COL_KEYWORD_STATE"], (DateTime?)reader["COL_KEYWORD_INSERT_TIME"], (DateTime?)reader["COL_KEYWORD_UPDATE_TIME"]);
                }
            }
            return model;
        }

        public string GetKeywordsXml() 
        {
            string cmd = "select distinct top 20 col_keyword_id, count(col_log_id) as logcount from uknow_keyword_log group by col_keyword_id order by logcount desc";
            StringBuilder builder = new StringBuilder("<keywords>");
            using (IDataReader reader = DBHelper.ExecuteReader(cmd))
            {
                while (reader.Read())
                {
                    MapKeyWordsModel keyword = GetLogKeyWordsModelByID((int)reader["col_keyword_id"]);
                    if (keyword == null) continue;

                    string comments = GetKeywordXml((int)reader["col_keyword_id"]);
                    if (string.IsNullOrEmpty(comments)) continue;

                    builder.AppendFormat("<keyword id=\"{0}\" text=\"{1}\">", keyword.ID, keyword.Name);
                    builder.Append(comments);
                    builder.AppendFormat("</keyword>");
                }
            }

            builder.Append("</keywords>");
            return builder.ToString();
        }

        public string GetKeywordXml(int keywordID)
        {
            string prefix = (this.Language.LanguageType == LanguageType.cn) ? "/cn" : "/en";
            string warmupUrl = prefix + "/interactivedetail.aspx?wid={0}&amp;currPageIndex=0&amp;sortType=null&amp;sortDirect=null";
            string eventsUrl = prefix + "/events/{0}.html";
            List<int> idList1 = new List<int>();

            StringBuilder builder = new StringBuilder();

            string cmd = string.Format("select * from uknow_keyword_log where col_keyword_id={0} and col_lang_id={1} order by COL_LOG_INSERT_TIME desc", keywordID, (int)Language.LanguageType);
            using (IDataReader reader = DBHelper.ExecuteReader(cmd))
            {
                while (reader.Read())
                {
                    int commentID = (int)reader["COL_COMMENT_ID"];
                    if ((int)reader["col_comment_type"] == 0 && !idList1.Contains(commentID) && idList1.Count < 2)
                    {
                        idList1.Add(commentID);
                        EventsCommentDAL dal = new EventsCommentDAL(this.Language.LanguageType);
                        EventsCommentModel model = dal.GetEventsCommentModelByID(commentID);
                        if (model != null)
                        {
                            string url = string.Format(eventsUrl, model.EventsID);
                            string img = (string.IsNullOrEmpty(model.Member.MemberImg)) ? "/uploadfiles/image/userhead_img.jpg" : "/uploadfiles/image/" + model.Member.MemberImg;
                            builder.AppendFormat("<cmt id=\"{0}\" uname=\"{1}\" time=\"{2}\" thumb=\"{3}\" url=\"{4}\"><![CDATA[{5}]]></cmt>",
                                model.ID, model.Member.Name, model.Time.ToString("yyyy-MM-dd HH:mm:ss"), img, url, model.Content);
                        }
                    }
                    else if ((int)reader["col_comment_type"] == 1 && !idList1.Contains(commentID) && idList1.Count < 2)
                    {
                        idList1.Add(commentID);
                        WarmupCommentDAL dal = new WarmupCommentDAL(this.Language.LanguageType);
                        WarmupCommentModel model = dal.GetWarmupCommentModelByID(commentID);
                        if (model != null)
                        {
                            string url = string.Format(warmupUrl, model.WarmupID);
                            string img = (model.Commenter.MemberImg == null) ? "/uploadfiles/image/userhead_img.jpg" : "/uploadfiles/image/" + model.Commenter.MemberImg;
                            builder.AppendFormat("<cmt id=\"{0}\" uname=\"{1}\" time=\"{2}\" thumb=\"{3}\" url=\"{4}\"><![CDATA[{5}]]></cmt>",
                                model.ID, model.Commenter.Name, model.Time.ToString("yyyy-MM-dd HH:mm:ss"), img, url, model.Text);
                        }
                    }
                }

            }

            return builder.ToString();
        }
    }

}
